/**
 * 专业DBC编辑器主类
 * 处理界面交互、文件操作和数据管理
 */

class DBCEditor {
    constructor() {
        this.database = new CANDatabase();
        this.selectedFrameId = null;
        this.selectedSignalName = null;
        this.isLoading = false;
        
        this.init();
        this.loadSampleData();
    }

    init() {
        this.bindEvents();
        this.updateInterface();
        console.log('🚀 DBC编辑器初始化完成');
    }

    bindEvents() {
        // 文件操作
        document.getElementById('openBtn').addEventListener('click', () => {
            document.getElementById('fileInput').click();
        });

        document.getElementById('fileInput').addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                this.loadDbcFile(file);
            }
        });

        document.getElementById('downloadBtn').addEventListener('click', () => {
            this.downloadDBC();
        });

        document.getElementById('fullscreenBtn').addEventListener('click', () => {
            this.toggleFullscreen();
        });

        // 表格操作
        document.getElementById('addMessageBtn').addEventListener('click', () => {
            this.addMessage();
        });

        document.getElementById('removeMessageBtn').addEventListener('click', () => {
            this.removeSelectedMessage();
        });

        document.getElementById('addSignalBtn').addEventListener('click', () => {
            this.addSignal();
        });

        document.getElementById('removeSignalBtn').addEventListener('click', () => {
            this.removeSelectedSignal();
        });

        // DBC预览切换
        document.getElementById('toggleDbcBtn').addEventListener('click', () => {
            this.toggleDbcPreview();
        });

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey) {
                switch (e.key) {
                    case 'o':
                        e.preventDefault();
                        document.getElementById('fileInput').click();
                        break;
                    case 's':
                        e.preventDefault();
                        this.downloadDBC();
                        break;
                    case 'f':
                        e.preventDefault();
                        this.toggleFullscreen();
                        break;
                }
            }
        });
    }

    loadSampleData() {
        // 测试简单DBC解析
        const testDbc = `VERSION ""

BU_: ECU1 ECU2

BO_ 291 Engine_Data: 8 ECU1
 SG_ Engine_RPM : 0|16@1+ (0.25,0) [0|8000] "rpm" ECU2
 SG_ Engine_Temp : 16|8@1- (1,-40) [-40|150] "degC" ECU2

BO_ 1110 Vehicle_Speed: 4 ECU1
 SG_ Vehicle_Speed : 0|16@1+ (0.1,0) [0|300] "km/h" ECU2
`;

        console.log('测试DBC内容:', testDbc);
        
        try {
            const tokenizer = new DBCTokenizer(testDbc);
            const parser = new DBCParser(tokenizer);
            this.database = parser.parse();
            
            console.log('解析结果:', this.database);
            this.updateInterface();
            this.setStatus('测试数据已加载', 'success');
        } catch (error) {
            console.error('测试DBC解析失败:', error);
            // 如果解析失败，使用手动创建的示例数据
            this.createManualSampleData();
        }
    }

    createManualSampleData() {
        // 创建示例数据
        const engineFrame = new CANFrame('Engine_Data', 0x123, 8, '发动机数据帧');
        const speedFrame = new CANFrame('Vehicle_Speed', 0x456, 4, '车速信息帧');

        // 创建示例信号
        const engineRpm = new CANSignal('Engine_RPM', 0, 16, 'Intel', 'unsigned', 0.25, 0, 0, 8000, 'rpm', '发动机转速');
        const engineTemp = new CANSignal('Engine_Temp', 16, 8, 'Intel', 'signed', 1, -40, -40, 150, '°C', '发动机温度');
        const vehicleSpeed = new CANSignal('Vehicle_Speed', 0, 16, 'Intel', 'unsigned', 0.1, 0, 0, 300, 'km/h', '车辆速度');

        // 添加信号到帧
        engineFrame.addSignal(engineRpm);
        engineFrame.addSignal(engineTemp);
        speedFrame.addSignal(vehicleSpeed);

        // 添加帧到数据库
        this.database.addFrame(engineFrame);
        this.database.addFrame(speedFrame);

        // 添加节点
        this.database.addNode('ECU1');
        this.database.addNode('ECU2');
        this.database.addNode('Gateway');

        this.updateInterface();
        this.setStatus('示例数据已加载', 'success');
    }

    async loadDbcFile(file) {
        if (this.isLoading) return;

        this.isLoading = true;
        this.showLoading(true);
        this.setStatus('正在解析DBC文件...', 'loading');

        try {
            const content = await this.readFileContent(file);
            console.log(`📁 开始解析文件: ${file.name} (${file.size} 字节)`);

            // 使用新的解析器
            const tokenizer = new DBCTokenizer(content);
            const parser = new DBCParser(tokenizer);
            
            this.database = parser.parse();
            this.database.filename = file.name;

            // 重置选择状态
            this.selectedFrameId = null;
            this.selectedSignalName = null;

            // 更新界面
            this.updateInterface();

            // 显示解析结果
            const stats = this.database.getStatistics();
            let message = `✅ DBC文件解析完成！\n\n`;
            message += `📊 统计信息:\n`;
            message += `• 消息数: ${stats.frameCount}\n`;
            message += `• 信号数: ${stats.signalCount}\n`;
            message += `• 节点数: ${stats.nodeCount}\n`;

            if (stats.warningCount > 0) {
                message += `\n⚠️ 警告: ${stats.warningCount} 个问题`;
                console.warn('解析警告:', this.database.warnings);
            }

            this.setStatus(`已加载: ${file.name}`, 'success');
            alert(message);

        } catch (error) {
            console.error('❌ 解析失败:', error);
            this.setStatus('解析失败', 'error');
            alert(`解析失败: ${error.message}`);
        } finally {
            this.isLoading = false;
            this.showLoading(false);
        }
    }

    readFileContent(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (e) => resolve(e.target.result);
            reader.onerror = () => reject(new Error('文件读取失败'));
            reader.readAsText(file, 'utf-8');
        });
    }

    updateInterface() {
        this.updateMessagesTable();
        this.updateSignalsTable();
        this.updateStatistics();
        this.updateDbcPreview();
        this.updateSignalPreview();
    }

    updateMessagesTable() {
        const tbody = document.querySelector('#messagesTable tbody');
        tbody.innerHTML = '';

        this.database.getAllFrames().forEach(frame => {
            const row = this.createMessageRow(frame);
            tbody.appendChild(row);
        });
    }

    createMessageRow(frame) {
        const row = document.createElement('tr');
        const isSelected = this.selectedFrameId === frame.canId;
        
        if (isSelected) {
            row.classList.add('selected-message');
        }

        const canIdHex = '0x' + frame.canId.toString(16).toUpperCase().padStart(3, '0');
        const frameType = frame.getFrameType();

        row.innerHTML = `
            <td>
                <input type="checkbox" ${isSelected ? 'checked' : ''} 
                       onchange="dbcEditor.toggleFrameSelection(${frame.canId})">
            </td>
            <td>
                <input type="text" value="${frame.name}" 
                       onchange="dbcEditor.updateFrame(${frame.canId}, 'name', this.value)">
            </td>
            <td>
                <input type="text" value="${canIdHex}" 
                       onchange="dbcEditor.updateFrame(${frame.canId}, 'canIdHex', this.value)">
            </td>
            <td>
                <input type="number" value="${frame.canId}" 
                       onchange="dbcEditor.updateFrame(${frame.canId}, 'canIdDec', this.value)">
            </td>
            <td>
                <select onchange="dbcEditor.updateFrame(${frame.canId}, 'type', this.value)">
                    <option value="Standard" ${frameType === 'Standard' ? 'selected' : ''}>Standard</option>
                    <option value="Extended" ${frameType === 'Extended' ? 'selected' : ''}>Extended</option>
                </select>
            </td>
            <td>
                <input type="number" min="1" max="8" value="${frame.dlc}" 
                       onchange="dbcEditor.updateFrame(${frame.canId}, 'dlc', this.value)">
            </td>
            <td>
                <input type="text" value="${frame.comment}" 
                       onchange="dbcEditor.updateFrame(${frame.canId}, 'comment', this.value)"
                       placeholder="消息注释">
            </td>
            <td>
                <button class="btn btn-sm btn-danger" onclick="dbcEditor.deleteFrame(${frame.canId})"
                        title="删除消息">🗑️</button>
            </td>
        `;

        row.style.cursor = 'pointer';
        row.onclick = (e) => {
            if (!e.target.matches('input, select, button')) {
                this.toggleFrameSelection(frame.canId);
            }
        };

        return row;
    }

    updateSignalsTable() {
        const tbody = document.querySelector('#signalsTable tbody');
        tbody.innerHTML = '';

        let signalsToShow = [];
        if (this.selectedFrameId) {
            const frame = this.database.getFrame(this.selectedFrameId);
            if (frame) {
                signalsToShow = frame.getAllSignals();
            }
        } else {
            // 显示所有信号
            this.database.getAllFrames().forEach(frame => {
                signalsToShow.push(...frame.getAllSignals());
            });
        }

        signalsToShow.forEach(signal => {
            const row = this.createSignalRow(signal);
            tbody.appendChild(row);
        });
    }

    createSignalRow(signal) {
        const row = document.createElement('tr');
        const isSelected = this.selectedSignalName === signal.name;
        
        if (isSelected) {
            row.classList.add('selected-signal');
        }

        // 确定模式
        let mode = 'Signal';
        if (signal.multiplexInfo) {
            if (signal.multiplexInfo === 'M') {
                mode = 'Multiplexor';
            } else if (signal.multiplexInfo.startsWith('m')) {
                mode = 'Multiplexed';
            }
        }

        row.innerHTML = `
            <td>
                <input type="checkbox" ${isSelected ? 'checked' : ''} 
                       onchange="dbcEditor.toggleSignalSelection('${signal.name}')">
            </td>
            <td>
                <input type="text" value="${signal.name}" 
                       onchange="dbcEditor.updateSignal('${signal.name}', 'name', this.value)">
            </td>
            <td>
                <select onchange="dbcEditor.updateSignal('${signal.name}', 'signedness', this.value)">
                    <option value="unsigned" ${signal.signedness === 'unsigned' ? 'selected' : ''}>unsigned</option>
                    <option value="signed" ${signal.signedness === 'signed' ? 'selected' : ''}>signed</option>
                </select>
            </td>
            <td>
                <select onchange="dbcEditor.updateSignal('${signal.name}', 'byteOrder', this.value)">
                    <option value="Intel" ${signal.byteOrder === 'Intel' ? 'selected' : ''}>Intel</option>
                    <option value="Motorola" ${signal.byteOrder === 'Motorola' ? 'selected' : ''}>Motorola</option>
                </select>
            </td>
            <td>
                <select onchange="dbcEditor.updateSignal('${signal.name}', 'mode', this.value)">
                    <option value="Signal" ${mode === 'Signal' ? 'selected' : ''}>Signal</option>
                    <option value="Multiplexor" ${mode === 'Multiplexor' ? 'selected' : ''}>Multiplexor</option>
                    <option value="Multiplexed" ${mode === 'Multiplexed' ? 'selected' : ''}>Multiplexed</option>
                </select>
            </td>
            <td>
                <input type="number" min="0" max="63" value="${signal.startBit}" 
                       onchange="dbcEditor.updateSignal('${signal.name}', 'startBit', this.value)">
            </td>
            <td>
                <input type="number" min="1" max="64" value="${signal.length}" 
                       onchange="dbcEditor.updateSignal('${signal.name}', 'length', this.value)">
            </td>
            <td>
                <input type="number" step="any" value="${signal.factor}" 
                       onchange="dbcEditor.updateSignal('${signal.name}', 'factor', this.value)">
            </td>
            <td>
                <input type="number" step="any" value="${signal.offset}" 
                       onchange="dbcEditor.updateSignal('${signal.name}', 'offset', this.value)">
            </td>
            <td>
                <input type="number" step="any" value="${signal.min}" 
                       onchange="dbcEditor.updateSignal('${signal.name}', 'min', this.value)">
            </td>
            <td>
                <input type="number" step="any" value="${signal.max}" 
                       onchange="dbcEditor.updateSignal('${signal.name}', 'max', this.value)">
            </td>
            <td>
                <input type="text" value="${signal.unit}" 
                       onchange="dbcEditor.updateSignal('${signal.name}', 'unit', this.value)"
                       placeholder="单位">
            </td>
            <td>
                <input type="text" value="${signal.comment}" 
                       onchange="dbcEditor.updateSignal('${signal.name}', 'comment', this.value)"
                       placeholder="信号注释">
            </td>
            <td>
                <button class="btn btn-sm btn-danger" onclick="dbcEditor.deleteSignal('${signal.name}')"
                        title="删除信号">🗑️</button>
            </td>
        `;

        row.style.cursor = 'pointer';
        row.onclick = (e) => {
            if (!e.target.matches('input, select, button')) {
                this.toggleSignalSelection(signal.name);
            }
        };

        return row;
    }

    updateStatistics() {
        const stats = this.database.getStatistics();
        
        document.getElementById('messageCount').textContent = `(${stats.frameCount})`;
        document.getElementById('signalCount').textContent = `(${stats.signalCount})`;
        document.getElementById('parseStats').textContent = 
            `统计: 消息 ${stats.frameCount}, 信号 ${stats.signalCount}, 节点 ${stats.nodeCount}`;
        
        // 更新选择信息
        let selectedInfo = '无选择';
        if (this.selectedFrameId) {
            const frame = this.database.getFrame(this.selectedFrameId);
            selectedInfo = `消息: ${frame ? frame.name : 'Unknown'}`;
            
            if (this.selectedSignalName) {
                selectedInfo += `, 信号: ${this.selectedSignalName}`;
            }
        }
        document.getElementById('selectedInfo').textContent = selectedInfo;
    }

    updateDbcPreview() {
        const preview = document.getElementById('dbcPreview');
        const content = this.generateDbcContent();
        preview.textContent = content;
        
        const lineCount = content.split('\n').length;
        document.getElementById('dbcLineCount').textContent = `(${lineCount}行)`;
    }

    generateDbcContent() {
        let content = '';
        
        // 版本信息
        content += `VERSION "${this.database.version || '1.0'}"\n\n`;
        
        // 新符号
        content += 'NS_ :\n';
        content += '\tNS_DESC_\n';
        content += '\tCM_\n';
        content += '\tBA_DEF_\n';
        content += '\tBA_\n';
        content += '\tVAL_\n';
        content += '\tCAT_DEF_\n';
        content += '\tCAT_\n';
        content += '\tFILTER\n\n';
        
        // 位时序
        content += 'BS_:\n\n';
        
        // 节点
        if (this.database.nodes.size > 0) {
            content += 'BU_:';
            this.database.nodes.forEach(node => {
                content += ` ${node}`;
            });
            content += '\n\n';
        }
        
        // 消息和信号
        this.database.getAllFrames().forEach(frame => {
            content += `BO_ ${frame.canId} ${frame.name}: ${frame.dlc} Vector__XXX\n`;
            
            frame.getAllSignals().forEach(signal => {
                const multiplexInfo = signal.multiplexInfo ? ` ${signal.multiplexInfo}` : '';
                const byteOrder = signal.byteOrder === 'Intel' ? '1' : '0';
                const signedness = signal.signedness === 'unsigned' ? '+' : '-';
                
                content += ` SG_ ${signal.name}${multiplexInfo} : ${signal.startBit}|${signal.length}@${byteOrder}${signedness} (${signal.factor},${signal.offset}) [${signal.min}|${signal.max}] "${signal.unit}"`;
                
                if (signal.receivers.length > 0) {
                    content += ` ${signal.receivers.join(',')}`;
                } else {
                    content += ' Vector__XXX';
                }
                content += '\n';
            });
            content += '\n';
        });
        
        // 注释
        this.database.getAllFrames().forEach(frame => {
            if (frame.comment) {
                content += `CM_ BO_ ${frame.canId} "${frame.comment}";\n`;
            }
            
            frame.getAllSignals().forEach(signal => {
                if (signal.comment) {
                    content += `CM_ SG_ ${frame.canId} ${signal.name} "${signal.comment}";\n`;
                }
            });
        });
        
        return content;
    }

    updateSignalPreview() {
        const preview = document.getElementById('signalPreview');
        
        if (!this.selectedSignalName || !this.selectedFrameId) {
            preview.innerHTML = '<div class="preview-info"><p>请选择一个信号查看预览</p></div>';
            return;
        }
        
        const frame = this.database.getFrame(this.selectedFrameId);
        const signal = frame ? frame.getSignal(this.selectedSignalName) : null;
        
        if (!signal) {
            preview.innerHTML = '<div class="preview-info"><p>无法找到选择的信号</p></div>';
            return;
        }
        
        preview.innerHTML = this.renderSignalPreview(signal);
    }

    renderSignalPreview(signal) {
        const maxBytes = 8;
        let html = '<div class="signal-info">';
        html += `<h4>信号: ${signal.name}</h4>`;
        html += `<p><strong>位置:</strong> 起始位 ${signal.startBit}, 长度 ${signal.length} 位</p>`;
        html += `<p><strong>属性:</strong> ${signal.byteOrder}, ${signal.signedness}</p>`;
        html += `<p><strong>转换:</strong> value × ${signal.factor} + ${signal.offset}</p>`;
        html += `<p><strong>范围:</strong> [${signal.min}, ${signal.max}] ${signal.unit}</p>`;
        html += '</div>';
        
        // 字节布局
        html += '<div class="byte-layout">';
        for (let byteIndex = 0; byteIndex < maxBytes; byteIndex++) {
            html += '<div class="byte-row">';
            html += `<div class="byte-label">字节 ${byteIndex}</div>`;
            html += '<div class="bit-grid">';
            
            for (let bitIndex = 7; bitIndex >= 0; bitIndex--) {
                const absoluteBit = byteIndex * 8 + bitIndex;
                const isSignalBit = absoluteBit >= signal.startBit && absoluteBit < signal.startBit + signal.length;
                
                html += `<div class="bit-cell ${isSignalBit ? 'signal' : ''}">${bitIndex}</div>`;
            }
            
            html += '</div>';
            html += '</div>';
        }
        html += '</div>';
        
        // 计算区域
        html += '<div class="calculation-area">';
        html += '<div class="calc-row">';
        html += '<span>数据 = 0x</span>';
        html += '<input type="text" class="calc-input" value="00" onchange="dbcEditor.calculateValue(this.value)">';
        html += '<span>= <span id="physicalValue">0.0</span> ' + signal.unit + '</span>';
        html += '</div>';
        html += '</div>';
        
        return html;
    }

    // 事件处理方法
    toggleFrameSelection(canId) {
        if (this.selectedFrameId === canId) {
            this.selectedFrameId = null;
            this.selectedSignalName = null;
        } else {
            this.selectedFrameId = canId;
            this.selectedSignalName = null;
        }
        this.updateInterface();
    }

    toggleSignalSelection(signalName) {
        if (this.selectedSignalName === signalName) {
            this.selectedSignalName = null;
        } else {
            this.selectedSignalName = signalName;
        }
        this.updateInterface();
    }

    updateFrame(canId, field, value) {
        const frame = this.database.getFrame(canId);
        if (!frame) return;

        try {
            switch (field) {
                case 'name':
                    this.database.framesByName.delete(frame.name);
                    frame.name = value;
                    this.database.framesByName.set(value, frame);
                    break;
                case 'canIdHex':
                    const newIdFromHex = parseInt(value, 16);
                    this.updateFrameId(frame, newIdFromHex);
                    break;
                case 'canIdDec':
                    const newIdFromDec = parseInt(value, 10);
                    this.updateFrameId(frame, newIdFromDec);
                    break;
                case 'dlc':
                    frame.dlc = parseInt(value);
                    break;
                case 'comment':
                    frame.setComment(value);
                    break;
            }
            this.updateDbcPreview();
        } catch (error) {
            console.error('更新帧信息时出错:', error);
        }
    }

    updateFrameId(frame, newId) {
        this.database.frames.delete(frame.canId);
        const oldId = frame.canId;
        frame.canId = newId;
        this.database.frames.set(newId, frame);
        
        if (this.selectedFrameId === oldId) {
            this.selectedFrameId = newId;
        }
    }

    updateSignal(signalName, field, value) {
        if (!this.selectedFrameId) return;

        const frame = this.database.getFrame(this.selectedFrameId);
        if (!frame) return;

        const signal = frame.getSignal(signalName);
        if (!signal) return;

        try {
            switch (field) {
                case 'name':
                    frame.signals.delete(signalName);
                    signal.name = value;
                    frame.signals.set(value, signal);
                    if (this.selectedSignalName === signalName) {
                        this.selectedSignalName = value;
                    }
                    break;
                case 'signedness':
                    signal.signedness = value;
                    break;
                case 'byteOrder':
                    signal.byteOrder = value;
                    break;
                case 'mode':
                    if (value === 'Multiplexor') {
                        signal.setMultiplexInfo('M');
                    } else if (value === 'Multiplexed') {
                        signal.setMultiplexInfo('m0');
                    } else {
                        signal.setMultiplexInfo(null);
                    }
                    break;
                case 'startBit':
                    signal.startBit = parseInt(value);
                    break;
                case 'length':
                    signal.length = parseInt(value);
                    break;
                case 'factor':
                    signal.factor = parseFloat(value);
                    break;
                case 'offset':
                    signal.offset = parseFloat(value);
                    break;
                case 'min':
                    signal.min = parseFloat(value);
                    break;
                case 'max':
                    signal.max = parseFloat(value);
                    break;
                case 'unit':
                    signal.unit = value;
                    break;
                case 'comment':
                    signal.setComment(value);
                    break;
            }
            this.updateSignalPreview();
            this.updateDbcPreview();
        } catch (error) {
            console.error('更新信号信息时出错:', error);
        }
    }

    deleteFrame(canId) {
        const frame = this.database.getFrame(canId);
        if (!frame) return;

        if (confirm(`确定要删除消息 "${frame.name}" 吗？这将同时删除该消息的所有信号。`)) {
            this.database.removeFrame(canId);
            
            if (this.selectedFrameId === canId) {
                this.selectedFrameId = null;
                this.selectedSignalName = null;
            }
            
            this.updateInterface();
        }
    }

    deleteSignal(signalName) {
        if (!this.selectedFrameId) return;

        const frame = this.database.getFrame(this.selectedFrameId);
        if (!frame) return;

        const signal = frame.getSignal(signalName);
        if (!signal) return;

        if (confirm(`确定要删除信号 "${signal.name}" 吗？`)) {
            frame.removeSignal(signalName);
            
            if (this.selectedSignalName === signalName) {
                this.selectedSignalName = null;
            }
            
            this.updateInterface();
        }
    }

    addMessage() {
        const name = prompt('请输入消息名称:', 'New_Message');
        if (!name) return;

        const canIdStr = prompt('请输入CAN ID (十六进制，如 0x123):', '0x100');
        if (!canIdStr) return;

        const canId = parseInt(canIdStr, 16);
        const dlc = parseInt(prompt('请输入DLC (1-8):', '8') || '8');

        if (this.database.hasFrame(canId)) {
            alert('该CAN ID已存在！');
            return;
        }

        const frame = new CANFrame(name, canId, dlc);
        this.database.addFrame(frame);
        this.updateInterface();
        this.setStatus(`已添加消息: ${name}`, 'success');
    }

    removeSelectedMessage() {
        if (!this.selectedFrameId) {
            alert('请先选择要删除的消息');
            return;
        }
        this.deleteFrame(this.selectedFrameId);
    }

    addSignal() {
        if (!this.selectedFrameId) {
            alert('请先选择一个消息来添加信号');
            return;
        }

        const name = prompt('请输入信号名称:', 'New_Signal');
        if (!name) return;

        const frame = this.database.getFrame(this.selectedFrameId);
        if (frame.hasSignal(name)) {
            alert('该信号名称已存在！');
            return;
        }

        const signal = new CANSignal(name, 0, 8, 'Intel', 'unsigned', 1, 0, 0, 255, '');
        frame.addSignal(signal);
        this.updateInterface();
        this.setStatus(`已添加信号: ${name}`, 'success');
    }

    removeSelectedSignal() {
        if (!this.selectedSignalName) {
            alert('请先选择要删除的信号');
            return;
        }
        this.deleteSignal(this.selectedSignalName);
    }

    calculateValue(hexValue) {
        if (!this.selectedSignalName || !this.selectedFrameId) return;

        const frame = this.database.getFrame(this.selectedFrameId);
        const signal = frame ? frame.getSignal(this.selectedSignalName) : null;
        
        if (!signal) return;

        try {
            const rawValue = parseInt(hexValue, 16);
            const extractedValue = signal.extractValue(rawValue);
            const physicalValue = signal.calculatePhysicalValue(extractedValue);
            
            const element = document.getElementById('physicalValue');
            if (element) {
                element.textContent = physicalValue.toFixed(3);
            }
        } catch (error) {
            console.error('计算错误:', error);
        }
    }

    downloadDBC() {
        const content = this.generateDbcContent();
        const filename = this.database.filename || 'exported.dbc';
        
        const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        
        this.setStatus(`已下载: ${filename}`, 'success');
    }

    toggleFullscreen() {
        if (document.fullscreenElement) {
            document.exitFullscreen();
            document.body.classList.remove('fullscreen');
        } else {
            document.documentElement.requestFullscreen();
            document.body.classList.add('fullscreen');
        }
    }

    toggleDbcPreview() {
        const content = document.querySelector('.dbc-content');
        content.style.display = content.style.display === 'none' ? 'block' : 'none';
    }

    setStatus(message, type = 'info') {
        const statusElement = document.getElementById('status');
        statusElement.textContent = message;
        statusElement.className = `status ${type}`;
        
        // 自动清除状态
        setTimeout(() => {
            if (statusElement.textContent === message) {
                statusElement.textContent = '就绪';
                statusElement.className = 'status';
            }
        }, 5000);
    }

    showLoading(show) {
        const overlay = document.getElementById('loadingOverlay');
        overlay.style.display = show ? 'flex' : 'none';
    }
}

// 全局实例和初始化
let dbcEditor;

document.addEventListener('DOMContentLoaded', () => {
    dbcEditor = new DBCEditor();
    console.log('🎉 DBC编辑器就绪');
}); 